﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace BaiduIndex.Class
{
    public class HttpHelper
    {
        public static string HttpGet(string url, IDictionary<string, string> parameters = null,
            string contentType = "application/json;charset=UTF-8")
        {
            HttpWebRequest request;
            if (parameters != null)
            {
                request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }

            request.Accept = "application/json, text/plain, */*";
            request.Method = "GET";
            // request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            // request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            request.Headers.Add("Cipher-Text", CipherStore.GetCipher);
            request.ReadWriteTimeout = 15000;
            request.ContentType = contentType;
            request.Host = "index.baidu.com";
            request.Referer = "https://index.baidu.com/v2/main/index.html";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.61";
            request.Headers.Add("Cookie", CookieStore.GetCookie);

            var response = (HttpWebResponse)request.GetResponse();
            var result = GetResponseAsString(response, Encoding.UTF8);
            return result;
        }

        public static string HttpPost(string url, string requestBody = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            request.Method = "GET";
            //request.ReadWriteTimeout = 15000;
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36 Edg/101.0.1210.32";
            request.Host = "data.chinaz.com";

            if (!string.IsNullOrEmpty(requestBody))
            {
                using (var postStream = new StreamWriter(request.GetRequestStream()))
                {
                    postStream.Write(requestBody);
                }
            }

            var response = (HttpWebResponse)request.GetResponse();
            var result = GetResponseAsString(response, Encoding.UTF8);
            return result;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <param name="encode"></param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters, string encode = "utf-8")
        {
            var postData = new StringBuilder();
            var hasParam = false;
            if (parameters == null) return postData.ToString();
            var dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                var name = dem.Current.Key;
                var value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (string.IsNullOrEmpty(name)) continue;
                if (hasParam)
                {
                    postData.Append("&");
                }

                postData.Append(name);
                postData.Append("=");
                switch (encode)
                {
                    case "gb2312":
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                        break;

                    case "utf8":
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                        break;

                    default:
                        postData.Append(value);
                        break;
                }

                hasParam = true;
            }

            dem.Dispose();
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(WebResponse rsp, Encoding encoding)
        {
            Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                if (stream != null) reader = new StreamReader(stream, encoding);
                if (reader != null) return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                reader?.Close();
                stream?.Close();
                rsp?.Close();
            }

            return "";
        }
    }
}